//
//  FibonacciSequence.m
//  iOS-Learning-Demo
//
//  Created by yuan xiaodong on 2022/3/21.
//  Copyright © 2022 yuan. All rights reserved.
//

#import "FibonacciSequence.h"

static const NSMutableArray<NSNumber *> *tempArray = nil;

@implementation FibonacciSequence

/**
 基本循环
 
 @param number n
 @return 斐波那契数值
 */
+ (NSInteger)normalFibonacci:(NSInteger)number {
    NSInteger a = 0, b = 1, c = 1;
    for (NSInteger i = 3; i <= number; i++) {
        a = b;
        b = c;
        c = a + b;
    }
    return c;
}

/**
 递归
 
 @param number n
 @return 斐波那契数值
 */
+ (NSInteger)recursionFibonacci:(NSInteger)number {
    
    if (number <= 0) {
        return 0;
    }
    if (number == 1) {
        return 1;
    }
    return [self recursionFibonacci:number - 1] + [self recursionFibonacci:number - 2];
}

/**
 递归记忆
 
 @param number n
 @return 斐波那契数值
 */
+ (NSInteger)memoryRecursionFibonacci:(NSInteger)number {
    
    // 记忆数组
    if (tempArray == nil) {
        tempArray = [NSMutableArray array];
    }
    NSInteger count = tempArray.count;
    if (count < number) {
        for (NSInteger i = count; i < number - count + 1; i++) {
            [tempArray addObject:@(-1)];
        }
        tempArray[0] = @(0);
        if (tempArray.count > 1) {
            tempArray[1] = @(1);
        }
    }
    
    // 值是-1的话，算出该位置的值
    if ([tempArray[number] integerValue] == -1) {
        tempArray[number] = @([self memoryRecursionFibonacci:number - 1] + [self memoryRecursionFibonacci:number - 2]);
    }
    // 返回记忆数组的值
    return [tempArray[number] integerValue];
}

@end

